package com.qding.park.adapter.bsg.adapter.impl;

import java.io.StringReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.qding.park.adapter.bsg.adapter.config.BSGConfig;
import com.qding.park.adapter.bsg.adapter.constant.ConstantFunction;
import com.qding.park.adapter.bsg.adapter.entity.ResponseMsg;
import com.qding.park.adapter.bsg.adapter.enums.ErrorCodeEnum;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.system.NetWorkException;
import com.qding.park.common.core.network.HttpUtil;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.target.common.adapter.PayFeeAdapter;
import com.qding.park.target.common.entity.AdMonthFeeOrder;
import com.qding.park.target.common.entity.AdTempPayOrder;
import com.qding.park.target.common.entity.AdTempPayResult;

/**
 * @ClassName PayFeeAdapterImpl
 * @Description TODO(缴费适配器实现)
 * @author Administrator
 * @Date 2016年8月28日 下午9:47:06
 * @version 1.0.0
 */
@Service("payFeeAdapter_12")
public class PayFeeAdapterImpl  implements PayFeeAdapter {
	private static final Log _log = LogFactory.getLog(PayFeeAdapterImpl.class);
	
	
	public PayFeeAdapterImpl(String url) {
	}
	
	public PayFeeAdapterImpl() {
    }

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see
	 * com.qding.park.target.common.adapter.PayFeeAdapter#createTempPayment(java
	 * .lang.String, java.lang.String) 创建 临停缴费单
	 */
	@Override
	public AdTempPayOrder createTempPayment(String parkId, String carNum,String userId) throws NetWorkException, AdapterException {
		try {
			String url = BSGConfig.getAdapterUrl();
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("clientID", parkId);
			jsonObj.put("cardCode", "");
			jsonObj.put("plateNo", carNum);
			jsonObj.put("flag", "2");
			Map<String, String> params = new HashMap<String, String>();
			params.put("UserID", "110");
			params.put("RequestFun", ConstantFunction.Parking_GetParkingMoney);
			params.put("RequestData", jsonObj.toJSONString());
			params.put("Sign", "ddd");
			_log.info("adapter request:"+params);
			String result = HttpUtil.doPost(url, params);
			_log.info("adapter response:"+result);
			java.io.Reader in = new StringReader(result);
			Document doc = (new SAXBuilder()).build(in);

			String temp = doc.getRootElement().getValue();
			in.close();
			ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
			String errorCode = repmsg.getErrorCode();
			if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
				throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
						ExceptionMessage.createExceptionMessage(
								AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
								ConstantFunction.Parking_GetParkingMoney + " adpater处理出错 :"+repmsg.getErrorMsg()));
			}
			JSONObject data = (JSONObject) repmsg.getResult();

			String enterTime = data.getString("enterTime");
			String parkingOrder = data.getString("parkingOrder");
			String parkingSerial = data.getString("parkingSerial");
			int parkingTime = Integer.valueOf(data.getString("parkingTime"));
			int payValue = Integer.valueOf(data.getString("payValue"));
			AdTempPayOrder apTempPayOrder = new AdTempPayOrder();
			apTempPayOrder.setEnterTime(DateUtils.parseDate(enterTime, DateUtils.DATE_LONG_DATE));
			apTempPayOrder.setOrderId(parkingOrder);
			apTempPayOrder.setParkingSerial(parkingSerial);
			apTempPayOrder.setParkingTime(parkingTime);
			apTempPayOrder.setPayValue(payValue);
			return apTempPayOrder;
		} catch (NetWorkException e) {
			throw e;
		} catch (AdapterException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public AdMonthFeeOrder calMonthFee(String parkId, int monthNum, String carNum)
			throws NetWorkException, AdapterException {
		try {
		    String url = BSGConfig.getAdapterUrl();
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("clientID", parkId);
			jsonObj.put("cardCode", "");
			jsonObj.put("plateNo", carNum);
			jsonObj.put("flag", "2");
			jsonObj.put("payMos", String.valueOf(monthNum));
			Map<String, String> params = new HashMap<String, String>();
			params.put("UserID", "110");
			params.put("RequestFun", ConstantFunction.Parking_MonthPayPrep);
			params.put("RequestData", jsonObj.toJSONString());
			params.put("Sign", "ddd");
			_log.info("adapter request:"+params);
			String result = HttpUtil.doPost(url, params);
			_log.info("adapter response:"+result);
			java.io.Reader in = new StringReader(result);
			Document doc = (new SAXBuilder()).build(in);

			String temp = doc.getRootElement().getValue();
			in.close();
			ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
			String errorCode = repmsg.getErrorCode();
			if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
				throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
						ExceptionMessage.createExceptionMessage(
								AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
								ConstantFunction.Parking_MonthPayPrep + " adpater处理出错 ："+repmsg.getErrorMsg()));
			}
			// {"startDate":"20161001","totalFee":"20000","expireDate":"20161031"}
			JSONObject data = (JSONObject) repmsg.getResult();
			AdMonthFeeOrder apMonthFeeOrder = new AdMonthFeeOrder();
			apMonthFeeOrder.setParkId(parkId);
			apMonthFeeOrder.setMonthNum(monthNum);
			apMonthFeeOrder.setTotalFee(Integer.valueOf(data.getString("totalFee")));
			apMonthFeeOrder.setStartTime(DateUtils.parseDate(data.getString("startDate"), DateUtils.DATE_SHORT_DATEONLY));
			apMonthFeeOrder
					.setExpireDate(DateUtils.parseDate(data.getString("expireDate"), DateUtils.DATE_SHORT_DATEONLY));
			System.out.println(data);
			return apMonthFeeOrder;
		} catch (NetWorkException e) {
			throw e;
		} catch (AdapterException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public void tempPaySuccessNotice(AdTempPayResult tempPayResult)
			throws NetWorkException, AdapterException {
		try {
		    String url = BSGConfig.getAdapterUrl();
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("clientID", tempPayResult.getParkCode());
			jsonObj.put("parkingOrder", tempPayResult.getOrderId());
			jsonObj.put("payTime", DateUtils.formatDate(tempPayResult.getPayTime(), DateUtils.DATE_LONG_DATE));
			jsonObj.put("payValue", tempPayResult.getRealAmount());
			Map<String, String> params = new HashMap<String, String>();
			params.put("UserID", "110");
			params.put("RequestFun", ConstantFunction.Parking_GetParkingMoneyResult);
			params.put("RequestData", jsonObj.toJSONString());
			params.put("Sign", "ddd");
			_log.info("adapter request:"+params);
			String result = HttpUtil.doPost(url, params);
			_log.info("adapter response:"+result);
			java.io.Reader in = new StringReader(result);
			Document doc = (new SAXBuilder()).build(in);

			String temp = doc.getRootElement().getValue();
			in.close();
			ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
			String errorCode = repmsg.getErrorCode();
			if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
				throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
						ExceptionMessage.createExceptionMessage(
								AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
								ConstantFunction.Parking_GetParkingMoneyResult + " adpater处理出错 :"+repmsg.getErrorMsg()));
			}
			// {"startDate":"20161001","totalFee":"20000","expireDate":"20161031"}
//			return new AdTempPayOrder();
		} catch (NetWorkException e) {
			throw e;
		} catch (AdapterException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public AdMonthFeeOrder monthPay(String parkId, String carNum, int monthNum, int amount, Date payDate,
			String chargePaidNo) throws NetWorkException, AdapterException {
		try {
		    String url = BSGConfig.getAdapterUrl();
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("clientID", parkId);
			jsonObj.put("cardCode", "");
			jsonObj.put("plateNo", carNum);
			jsonObj.put("flag", "2");
			jsonObj.put("payMos", String.valueOf(monthNum));
			jsonObj.put("amount", String.valueOf(amount));
			jsonObj.put("payDate", DateUtils.formatDate(payDate, DateUtils.DATE_LONG_DATE));
			jsonObj.put("chargePaidNo", chargePaidNo);
			Map<String, String> params = new HashMap<String, String>();
			params.put("UserID", "110");
			params.put("RequestFun", ConstantFunction.Parking_MonthlyFee);
			params.put("RequestData", jsonObj.toJSONString());
			params.put("Sign", "ddd");
			_log.info("adapter request:"+params);
			String result = HttpUtil.doPost(url, params);
			_log.info("adapter response:"+result);
			java.io.Reader in = new StringReader(result);
			Document doc = (new SAXBuilder()).build(in);

			String temp = doc.getRootElement().getValue();
			in.close();
			ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
			String errorCode = repmsg.getErrorCode();
			if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
				throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
						ExceptionMessage.createExceptionMessage(
								AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
								ConstantFunction.Parking_MonthlyFee + " adpater处理出错 :"+repmsg.getErrorMsg()));
			}
			// {"startDate":"20161001","totalFee":"20000","expireDate":"20161031"}
			JSONObject data = (JSONObject) repmsg.getResult();
			AdMonthFeeOrder apMonthFeeOrder = new AdMonthFeeOrder();
			apMonthFeeOrder.setCarNum(carNum);
			apMonthFeeOrder
					.setExpireDate(DateUtils.parseDate(data.getString("expireDate"), DateUtils.DATE_SHORT_DATEONLY));
			return apMonthFeeOrder;
		} catch (NetWorkException e) {
			throw e;
		} catch (AdapterException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

}
